package com.scalar.chiptrack.finance.proformainvoice.actioncommands;

import com.scalar.chiptrack.actioncommands.ActionCommand;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.Address;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.finance.proformainvoice.forms.ProformaInvoiceForm;
import com.scalar.chiptrack.finance.proformainvoice.dao.ProformaInvoiceDAO;
import com.scalar.chiptrack.finance.proformainvoice.ProformaInvoiceHelper;
import com.scalar.chiptrack.sales.SalesOrder;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Date;
import java.util.ArrayList;

/**
 * User: KP
 * Date: Sep 28, 2006
 * Time: 3:10:16 PM
 */
public class ProformaInvoiceLoadSalesOrderCommand extends ActionCommand
{
    private static final String ACTION_NAME = "/newproformaInvoice.do";

    public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception
    {

        try {
            request.setCharacterEncoding( "UTF-8" );
        } catch (UnsupportedEncodingException e) { }

        /*
            Variable 'refreshedByPopUpScreen' used to determine from which source (after pulling from new fab lots scr OR after clicking 'Back' button in approval(print view) screen)
        */
        String forward                  = "new";
        String action                   = request.getParameter("action");
        String salesOrderId             = request.getParameter("salesOrderId");
        String refreshedByUser          = request.getParameter("refreshedByUser");

        salesOrderId  = "1054";

        HashMap errors = ( HashMap ) request.getAttribute( ERROR_MESSAGES );
        HashMap info   = ( HashMap ) request.getAttribute( INFO_MESSAGES );

        HttpSession mSession = request.getSession();
        User user = ( User ) mSession.getAttribute ( SessionKeys.USER_KEY );

        ProformaInvoiceForm invoiceForm = ( ProformaInvoiceForm ) form;
        SalesOrder salesOrder           = null;
        int salesOrderIdInt             = 0;
        HashMap bankInfoMap = new HashMap();

        if ( user == null )
        {
            mSession.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME);
            return ( mapping.findForward ( "login" ) );
        }
        else
        {
            if ( user.isActionAllowed ( Functionality.TEST_RELEASE , User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage", "TRUE" );
            }
        }
        request.setAttribute( "actionType", action );
        request.setAttribute( "action", action );

        try
        {
            salesOrderIdInt = Integer.parseInt( salesOrderId );
        }catch( NumberFormatException nfe ) {};

        try
        {
            int finalbankId = 0;
                String bankId = request.getParameter("bankId");

                if( bankId != null && bankId.trim().length() != 0 )
    	        {
			       finalbankId = Integer.parseInt(bankId);
	        	}
            salesOrder = SalesOrderDAO.loadSalesOrder( invoiceForm.getSalesOrderId() + "" );
            ArrayList lineItemList = ProformaInvoiceDAO.loadLineItemDetails( null, invoiceForm.getSalesOrderId(), -1 );

            ProformaInvoiceHelper.resetProformaInvoiceForm( invoiceForm );

            if( lineItemList != null && lineItemList.size() > 0 )
            {
                invoiceForm.setInvoiceNo( ProformaInvoiceDAO.generateAutomatedProformaInvoiceNo() );
                invoiceForm.setSalesOrderId( salesOrder.getSalesOrderId() );
                invoiceForm.setSalesOrder( salesOrder );
                invoiceForm.setInvoiceDate( StringUtils.formatDateToString( new Date(), "MM/dd/yyyy" ) );
                invoiceForm.setLineItemList( lineItemList );
                invoiceForm.setBankAddress( new Address() );
                finalbankId = UserDAO.loadBankId();
                bankInfoMap = UserDAO.loadClientBankAddressDetails( null , finalbankId );
			    request.setAttribute( "BankInfo" , bankInfoMap );
                request.setAttribute( "AllBankNames", UserDAO.getAllBankNames());
            }
            else
            {
                errors.put( "Could not created Proforma Invoice since line item quanity is not sufficient", null );

                request.setAttribute( "salesOrderList", ProformaInvoiceDAO.loadApprovedSalesOrderList( null ) );
                request.setAttribute( "customerList", CustomerDAO.getAllCustomerNamesByUserType( null, user ) );
                request.setAttribute ( "productList", ProformaInvoiceDAO.loadManufacturingProducts() );
                request.setAttribute ( "years", SalesOrderDAO.getYearList () );
                request.setAttribute( "salesOrderCustomerPOList", ProformaInvoiceDAO.loadApprovedSalesOrderCustomerPOList( null ) );
                forward = "search_orders_for_new_invoice";

            }

        }
        catch( Exception e )
        {
            e.printStackTrace();
            errors.put( "Could not create new Proforma Invoice", null );
            forward = "search_orders_for_new_invoice";
            try
            {
                request.setAttribute( "salesOrderList", ProformaInvoiceDAO.loadApprovedSalesOrderList( null ) );
                request.setAttribute( "customerList", CustomerDAO.getAllCustomerNamesByUserType( null, user ) );
                request.setAttribute ( "productList", ProformaInvoiceDAO.loadManufacturingProducts() );
                request.setAttribute( "salesOrderCustomerPOList", ProformaInvoiceDAO.loadApprovedSalesOrderCustomerPOList( null ) );
            }
            catch(Exception ee){ }
        }

        saveToken( request );

        return mapping.findForward( forward );
    }
}
